<?php

namespace app\admin\controller;

use app\api\controller\Base;
use app\api\library\WeChat\MiniProgram;
use app\api\library\WeChat\Payment;
use app\api\model\User as UserModel;
use app\common\controller\Backend;
use app\common\controller\Messages;
use app\common\enum\TemplateEnum;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use \app\api\model\Order as OrderModel;
use think\Log;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("tkOrderList", $this->model->getTkOrderList());
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['User'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['User'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if ($params['tk_order'] == 2) {
                        $openId = (new UserModel())->where('id', '=', $row['user_id'])->value('openid'); //提醒的用户openid
                        $refund_number = 'tk' . (new Base())->makeOrderNo(); //退款单号
                        if ($params['old_status'] == 1) { //如果是待核销
                            $res = (new Payment())->refund($row['order_number'], $refund_number, $row['order_price'] * 100, $row['order_price'] * 100);//拉起退款
                            $this->rel_code($res, $row['id']); //修改订单状态为已取消
                            $tmp = (new Messages())->refund($row); //消息模板
                            (new MiniProgram())->templateMessage(TemplateEnum::Tmp_REFUND, $openId, '/', $tmp); //订阅消息
                            }
                    }


                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //退款成功回调
    public function rel_code($data, $orderId)
    {
        if ($data['return_code'] == "SUCCESS") {
            $this->refundStatus($orderId); //修改订单状态为已取消
        } else {
            parent::error('退款失败', $data['return_msg']);
        }
    }

    //修改退款后的状态
    public function refundStatus($orderId)
    {
        $refund_number = 'tk' . (new Base())->makeOrderNo(); //退款单号
        return (new OrderModel())->where('id', '=', $orderId)->update([
            'status' => 4,//已取消
            'tk_number' => $refund_number
        ]);

    }


}
